package org.example;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.util.Random;

@Aspect
@Component
public class OrderServiceAspect {

    // 1. 对add, delete, find方法进行前置增强
    @Before("execution(* org.example.OrderService.*(..))")
    public void beforeAdvice() {
        System.out.println("hello, 我是一个前置增强");
    }

    // 2. 对add, delete方法执行后进行后置增强
    @After("execution(* org.example.OrderService.add(..)) || execution(* org.example.OrderService.delete(..))")
    public void afterAdvice() {
        System.out.println("bye, 我是一个后置增强");
    }

    // 3. 对add, delete, find方法获取返回值并输出
    @AfterReturning(pointcut = "execution(* org.example.OrderService.*(..))", returning = "result")
    public void afterReturningAdvice(Object result) {
        System.out.println("方法返回值为: " + result);
    }

    // 4. 对add, delete, find方法输出执行时间
    @Around("execution(* org.example.OrderService.*(..))")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        try {
            Object result = joinPoint.proceed();
            return result;
        } finally {
            long endTime = System.currentTimeMillis();
            System.out.println("方法 " + joinPoint.getSignature().getName() + " 执行时间为: " + (endTime - startTime) + " 毫秒");
        }
    }

    // 5. 在add, delete方法执行前进行权限检查
    @Around("execution(* org.example.OrderService.add(..)) || execution(* org.example.OrderService.delete(..))")
    public Object checkPermission(ProceedingJoinPoint joinPoint) throws Throwable {
        Random random = new Random();
        int permission = random.nextInt(2); // 生成0或1的随机数

        if (permission == 0) {
            System.out.println("权限检查通过");
            return joinPoint.proceed();
        } else {
            System.out.println("权限检查失败，没有权限执行 " + joinPoint.getSignature().getName() + " 方法");
            return null;
        }
    }
}
